package com.alfred.mall.product.biz.convert;

import com.alfred.common.framwork.util.StringUtil;
import com.alfred.mall.product.api.bo.ProductAttrAndValuePairBO;
import com.alfred.mall.product.api.bo.ProductSkuDetailBO;
import com.alfred.mall.product.biz.dataobject.ProductSkuDO;
import com.alfred.mall.product.biz.dataobject.ProductSpuDO;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Mapper
public interface ProductSpuConvert {

    ProductSpuConvert INSTANCE = Mappers.getMapper(ProductSpuConvert.class);

    @Mappings({@Mapping(source = "picUrls", target = "picUrls", ignore = true)})
    ProductSkuDetailBO.Spu convert3(ProductSpuDO spu);

    @Mappings({@Mapping(source = "attrs", target = "attrs", ignore = true)})
    ProductSkuDetailBO convert3(ProductSkuDO sku);

    default List<ProductSkuDetailBO> convert3(List<ProductSkuDO> skus, List<ProductSpuDO> spus, List<ProductAttrAndValuePairBO> productAttrDetailBOs) {
        // 创建 ProductAttrDetailBO 的映射。其中，KEY 为 ProductAttrDetailBO.attrValueId ，即规格值的编号
        Map<Integer, ProductAttrAndValuePairBO> productAttrDetailBOMap = productAttrDetailBOs.stream().collect(
                Collectors.toMap(ProductAttrAndValuePairBO::getAttrValueId, productAttrDetailBO -> productAttrDetailBO));
        // 创建 ProductSpuDO 的映射
        Map<Integer, ProductSkuDetailBO.Spu> spuMap = spus.stream().collect(
                Collectors.toMap(ProductSpuDO::getId, spu -> ProductSpuConvert.this.convert3(spu).setPicUrls(StringUtil.split(spu.getPicUrls(), ","))));


        List<ProductSkuDetailBO> spuDetailList = new ArrayList<>(skus.size());
        for (ProductSkuDO sku : skus) {
            ProductSkuDetailBO skuDetail = ProductSpuConvert.this.convert3(sku)
                    .setAttrs(new ArrayList<>())
                    .setPicUrl(sku.getPicUrl())
                    .setSpu(spuMap.get(sku.getSpuId()));
            spuDetailList.add(skuDetail);
            List<String> attrs = StringUtil.split(sku.getAttrs(), ",");
            attrs.forEach(attr -> skuDetail.getAttrs().add(productAttrDetailBOMap.get(Integer.valueOf(attr))));
        }
        return spuDetailList;
    }
}
